package zheezes.eisp.monitor.view;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.log4j.PropertyConfigurator;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.beans.BeansObservables;
import org.eclipse.core.databinding.conversion.NumberToStringConverter;
import org.eclipse.core.databinding.conversion.StringToNumberConverter;
import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.core.databinding.observable.list.WritableList;
import org.eclipse.core.databinding.observable.map.IObservableMap;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.StatusLineManager;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.databinding.viewers.ObservableListContentProvider;
import org.eclipse.jface.databinding.viewers.ObservableListTreeContentProvider;
import org.eclipse.jface.databinding.viewers.ObservableMapLabelProvider;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tray;
import org.eclipse.swt.widgets.TrayItem;
import org.springframework.context.ApplicationContext;

import zheezes.eisp.ImageRegistryFactory;
import zheezes.eisp.LocaleResources;
import zheezes.eisp.data.dao.DataAccessor;
import zheezes.eisp.data.orm.Concentrator;
import zheezes.eisp.data.orm.FramePo;
import zheezes.eisp.data.orm.GroupPo;
import zheezes.eisp.fep.model.Commander;
import zheezes.eisp.monitor.model.FrameVo;
import zheezes.eisp.monitor.model.TaskListFactory;
import zheezes.eisp.monitor.model.TaskVo;
import zheezes.eisp.monitor.model.TermListFactory;
import zheezes.eisp.monitor.model.TermVo;
import zheezes.eisp.monitor.model.TreeFactory;
import zheezes.eisp.util.SpringUtil;
import zheezes.model.ObservableTreeNode;
import zheezes.swt.converter.BooleanConverter;
import zheezes.swt.databinding.BeansListObservableFactory;
import zheezes.swt.databinding.TreeBeanAdvisor;
import zheezes.swt.databinding.TreeObservableLabelProvider;
import zheezes.swt.util.FieldViewerSorter;
import zheezes.swt.util.SWTUtil;


public class ToolkitWindow extends ApplicationWindow {
	private Action deleteconAction;
	private Action refreshallframesAction;
	private Action refreshtasktableAction;
	private Action refreshtermtableAction;
	private Action reloadnavitreeAction;
	private Table table;
	private Action getFepConnNumAction;
	private Text udpText;
	private Text tcpText;
	private Text portText;
	private Text hostText;
	private Action disconnectfepAction;
	private Action connectFepAction;
	private Action preferencesAction;
	private Action aboutAction;
	private Action welcomeAction;
	private Action showOrHideAction;
	private ResourceBundle resourceBundle;
	private Display display;
	private ImageRegistry imageRegistry;
	private Tray tray;
	private TrayItem trayItem;
	private Action hideWindowAction;
	private Action showWindowAction;
	private Action maximizeAction;
	private Action minimizeAction;
	private Action deleteTaskAction;
	private TableViewer taskTableViewer;
	private Table taskTable;
	private Action exitAction;
	private TableViewer termTableViewer;
	private Table termTable;
	private TreeViewer naviTreeViewer;
	private TableViewer frameTableViewer;
	private DataBindingContext bindingContext;
	private Commander commander = new Commander();
	private Group funcGroup;
	private Button connectButton;
	private Button closeButton;
	private DataAccessor dataAccessor;

	private TreeFactory treeFactory;
	private List<ObservableTreeNode> treeData;
	private TermListFactory termListFactory;
	private List<TermVo> termList;
	private TaskListFactory taskListFactory;
	private List<TaskVo> taskList;

	public ToolkitWindow() {
		super(null);
		init();
	}

	public ToolkitWindow(ResourceBundle resourceBundle) {
		super(null);
		this.resourceBundle = resourceBundle;
		init();
	}

	private void init() {
		createActions();
		addToolBar(SWT.FLAT | SWT.WRAP);
		addMenuBar();
		addStatusLine();
	}

	protected boolean canHandleShellCloseEvent() {
		return false;
	}

	@Override
	protected Control createContents(Composite parent) {
		display = getShell().getDisplay();

		tray = display.getSystemTray();
		if (tray != null) {
			trayItem = new TrayItem(tray, SWT.NONE);
			trayItem.setToolTipText(resourceBundle
					.getString(LocaleResources.PROGRAM_TOOLKIT_TITLE));
			trayItem.setImage(imageRegistry
					.get(ImageRegistryFactory.IMAGE_KAIFA_LOGO));

			final MenuManager trayMenuManager = new MenuManager();
			// menuManager.add(trayMenuManager);
			trayMenuManager.add(hideWindowAction);
			trayMenuManager.add(showWindowAction);
			trayMenuManager.add(exitAction);
			final Menu menu = trayMenuManager.createContextMenu(getShell());
			trayItem.addListener(SWT.DefaultSelection, new Listener() {
				public void handleEvent(Event e) {
					showOrHideAction.run();
				}
			});
			trayItem.addListener(SWT.MenuDetect, new Listener() {
				public void handleEvent(Event e) {
					menu.setVisible(true);
				}
			});
			getShell().addShellListener(new ShellAdapter() {
				public void shellClosed(ShellEvent e) {
					hideWindowAction.run();
				}
			});
		}

		Composite container = new Composite(parent, SWT.NONE);
		container.setLayout(new GridLayout());

		final SashForm sashForm = new SashForm(container, SWT.NONE);
		final GridLayout sashFormGridLayout = new GridLayout(2, false);
		sashForm.setLayout(sashFormGridLayout);
		sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));

		naviTreeViewer = new TreeViewer(sashForm, SWT.BORDER);
		naviTreeViewer.setUseHashlookup(true);
		naviTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
			public void selectionChanged(final SelectionChangedEvent event) {
				IStructuredSelection selection = (IStructuredSelection) event
						.getSelection();
				ObservableTreeNode node = (ObservableTreeNode) selection
						.getFirstElement();
				Object data = node.getData();
				if (data instanceof GroupPo) {
					GroupPo group = (GroupPo) data;
					setStatus(group.getName());
				} else if (data instanceof Concentrator) {
					Concentrator con = (Concentrator) data;
					setStatus(con.getLogicAddr());
				}
			}
		});

		final CTabFolder tabFolder = new CTabFolder(sashForm, SWT.NONE);

		final CTabItem termTabItem = new CTabItem(tabFolder, SWT.NONE);
		termTabItem.setText(resourceBundle.getString(LocaleResources.TAB_TERM));

		termTableViewer = new TableViewer(tabFolder, SWT.MULTI | SWT.BORDER
				| SWT.FULL_SELECTION | SWT.CENTER);
		termTable = termTableViewer.getTable();
		termTable.setLinesVisible(true);
		termTable.setHeaderVisible(true);
		termTabItem.setControl(termTable);

		final CTabItem taskTabItem = new CTabItem(tabFolder, SWT.NONE);
		taskTabItem.setText(resourceBundle.getString(LocaleResources.TAB_TASK));

		taskTableViewer = new TableViewer(tabFolder, SWT.MULTI | SWT.BORDER
				| SWT.FULL_SELECTION | SWT.CENTER);
		taskTable = taskTableViewer.getTable();
		taskTable.setLinesVisible(true);
		taskTable.setHeaderVisible(true);
		final MenuManager taskMenuManager = new MenuManager();
		// menuManager.add(termMenuManager);
		taskMenuManager.add(deleteTaskAction);
		taskTable.setMenu(taskMenuManager.createContextMenu(taskTable));
		taskTabItem.setControl(taskTable);

		final CTabItem framesTabItem = new CTabItem(tabFolder, SWT.NONE);
		framesTabItem.setText("frames");

		frameTableViewer = new TableViewer(tabFolder, SWT.BORDER);
		table = frameTableViewer.getTable();
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		framesTabItem.setControl(table);

		final TableColumn newColumnTableColumn = new TableColumn(table, SWT.RIGHT);
		newColumnTableColumn.setAlignment(SWT.RIGHT);
		newColumnTableColumn.setWidth(100);
		newColumnTableColumn.setText("New column");

		final TableColumn newColumnTableColumn_1 = new TableColumn(table, SWT.CENTER);
		newColumnTableColumn_1.setAlignment(SWT.CENTER);
		newColumnTableColumn_1.setWidth(100);
		newColumnTableColumn_1.setText("New column");

		final CTabItem fepTabItem = new CTabItem(tabFolder, SWT.NONE);
		fepTabItem.setText(resourceBundle.getString(LocaleResources.VAR_FEP));
		
		final ScrolledComposite scrolledComposite = new ScrolledComposite(tabFolder, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
		scrolledComposite.setMinWidth(400);
		scrolledComposite.setMinHeight(300);
		scrolledComposite.setExpandVertical(true);
		scrolledComposite.setExpandHorizontal(true);
		scrolledComposite.setLayout(new FillLayout());
		
		final Composite composite = new Composite(scrolledComposite, SWT.BORDER | SWT.FILL);
		final GridLayout gridLayout = new GridLayout(1, true);
		gridLayout.marginHeight = 0;
		gridLayout.marginWidth = 0;
		composite.setLayout(gridLayout);

		final Group connectionGroup = new Group(composite, SWT.NONE);
		connectionGroup.setText(resourceBundle.getString(LocaleResources.VAR_CONNECTION));
		final GridLayout connGroupGridLayout = new GridLayout(6, false);
		connGroupGridLayout.marginWidth = 0;
		connectionGroup.setLayout(connGroupGridLayout);
		
		final GridData connectionGroupGridData = new GridData(SWT.FILL, SWT.CENTER, true, false);
		connectionGroupGridData.heightHint = 30;
		connectionGroup.setLayoutData(connectionGroupGridData);

		final CLabel hostLabel = new CLabel(connectionGroup, SWT.CENTER);
		hostLabel.setLayoutData(new GridData(50, SWT.DEFAULT));
		hostLabel.setText(resourceBundle.getString(LocaleResources.VAR_FEP_HOST));
		
		hostText = new Text(connectionGroup, SWT.BORDER);
		final GridData gd_hostText = new GridData(SWT.FILL, SWT.CENTER, false, false);
		gd_hostText.widthHint = 90;
		hostText.setLayoutData(gd_hostText);
		hostText.setTextLimit(15);

		final CLabel portLabel = new CLabel(connectionGroup, SWT.NONE);
		final GridData gd_portLabel = new GridData(SWT.CENTER, SWT.CENTER, false, false);
		gd_portLabel.widthHint = 65;
		portLabel.setLayoutData(gd_portLabel);
		portLabel.setText(resourceBundle.getString(LocaleResources.VAR_FEP_LSNR_PORT));

		portText = new Text(connectionGroup, SWT.BORDER);
		final GridData portTextGridData = new GridData(SWT.FILL, SWT.CENTER, false, false);
		portTextGridData.widthHint = 30;
		portText.setLayoutData(portTextGridData);
		portText.setTextLimit(5);
		
		connectButton = new Button(connectionGroup, SWT.NONE);
		connectButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				connectFepAction.run();
			}
		});
		connectButton.setText(resourceBundle.getString(LocaleResources.VAR_CONNECT));

		closeButton = new Button(connectionGroup, SWT.NONE);
		closeButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				disconnectfepAction.run();
			}
		});
		closeButton.setText(resourceBundle.getString(LocaleResources.VAR_DISCONNECT));

		funcGroup = new Group(composite, SWT.NONE);
		funcGroup.setText(resourceBundle.getString(LocaleResources.VAR_FUNCTIONS));
		final GridLayout funcGroupGridLayout = new GridLayout(5, false);
		funcGroupGridLayout.marginWidth = 0;
		funcGroup.setLayout(funcGroupGridLayout);
		final GridData funcGroupGridData = new GridData(SWT.FILL, SWT.FILL, true, true);
		funcGroup.setLayoutData(funcGroupGridData);

		final CLabel tcpLabel = new CLabel(funcGroup, SWT.CENTER);
		tcpLabel.setLayoutData(new GridData(30, SWT.DEFAULT));
		tcpLabel.setText(resourceBundle.getString(LocaleResources.VAR_TCP));

		tcpText = new Text(funcGroup, SWT.BORDER);
		tcpText.setEditable(false);
		final GridData tcpTextGridData = new GridData();
		tcpText.setLayoutData(tcpTextGridData);

		final CLabel udpLabel = new CLabel(funcGroup, SWT.NONE);
		final GridData gd_udpLabel = new GridData(SWT.FILL, SWT.CENTER, false, false);
		gd_udpLabel.widthHint = 30;
		udpLabel.setLayoutData(gd_udpLabel);
		udpLabel.setText(resourceBundle.getString(LocaleResources.VAR_UDP));

		udpText = new Text(funcGroup, SWT.BORDER);
		udpText.setEditable(false);
		final GridData udpTextGridData = new GridData(SWT.FILL, SWT.CENTER, false, false);
		udpText.setLayoutData(udpTextGridData);

		final Button countFepConnectionsButton = new Button(funcGroup, SWT.NONE);
		countFepConnectionsButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				Map<String, Integer> map = commander.count();
				if (map != null) {
					Integer tcp = map.get("tcp");
					Integer udp = map.get("udp");
					if (tcp != null) {
						tcpText.setText(tcp.toString());
					} else {
						tcpText.setText("");
					}
					if (udp != null) {
						udpText.setText(udp.toString());
					} else {
						udpText.setText("");
					}
				}
			}
		});
		countFepConnectionsButton.setText(resourceBundle.getString(LocaleResources.VAR_FEP_CONN_COUNT));
		
		scrolledComposite.setContent(composite);
		
		fepTabItem.setControl(scrolledComposite);
		
		tabFolder.setSelection(0);
		
		sashForm.setWeights(new int[] { 1, 3 });

		for (final String field : TermVo.fields()) {
			TableColumn column = new TableColumn(termTable, SWT.CENTER);
			column.setWidth(150);
			column.setText(resourceBundle.getString(TermVo.getLabel(field)));
			column.addSelectionListener(new SelectionAdapter() {
				private boolean asc = true;

				public void widgetSelected(SelectionEvent e) {
					FieldViewerSorter sorter = new FieldViewerSorter();
					sorter.setName(field);
					sorter.setAsc(asc);
					asc = !asc;
					termTableViewer.setSorter(sorter);
				}
			});
		}

		for (String lstr : new String[] { 
				LocaleResources.TASK_COLUMN_TYPE,
				LocaleResources.TASK_COLUMN_DATE }) {
			TableColumn column = new TableColumn(taskTable, SWT.CENTER);
			column.setAlignment(SWT.CENTER);
			column.setWidth(150);
			column.setText(resourceBundle.getString(lstr));
		}

		bindingContext = initDataBindings();
		return container;
	}

	private void createActions() {
		exitAction = new Action(resourceBundle
				.getString(LocaleResources.ACTION_EXIT)) {
			public void run() {
				trayItem.dispose();
				handleShellCloseEvent();
			}
		};

		deleteTaskAction = new Action(resourceBundle
				.getString(LocaleResources.ACTION_TASK_DELETE)) {
			public void run() {
				IStructuredSelection selection = (IStructuredSelection) taskTableViewer
						.getSelection();
				TaskVo taskVo = null;
				if (!selection.isEmpty()) {
					Iterator iter = selection.iterator();
					while (iter.hasNext()) {
						taskVo = (TaskVo) iter.next();
						if (dataAccessor.deleteCollectTask(taskVo.getModel().getId()) == 0) {
							taskList.remove(taskVo);
							taskTableViewer.remove(taskVo);
						}
					}
				}
			}
		};

		minimizeAction = new Action(resourceBundle
				.getString(LocaleResources.ACTION_WINDOW_MINIMIZE)) {
			public void run() {
				getShell().setMinimized(true);
			}
		};

		maximizeAction = new Action(resourceBundle
				.getString(LocaleResources.ACTION_WINDOW_MAXIMIZE)) {
			public void run() {
				getShell().setMaximized(true);
			}
		};

		showWindowAction = new Action(resourceBundle
				.getString(LocaleResources.ACTION_WINDOW_SHOW)) {
			public void run() {
				getShell().setVisible(true);
				getShell().setActive();
				hideWindowAction.setEnabled(true);
				this.setEnabled(false);
			}
		};
		showWindowAction.setEnabled(false);

		hideWindowAction = new Action(resourceBundle
				.getString(LocaleResources.ACTION_WINDOW_HIDE)) {
			public void run() {
				getShell().setVisible(false);
				showWindowAction.setEnabled(true);
				this.setEnabled(false);
			}
		};

		showOrHideAction = new Action(resourceBundle
				.getString(LocaleResources.ACTION_WINDOW_SHOWORHIDE)) {
			public void run() {
				if (getShell().isVisible()) {
					hideWindowAction.run();
				} else {
					showWindowAction.run();
				}
			}
		};

		welcomeAction = new Action(resourceBundle
				.getString(LocaleResources.ACTION_WELCOME)) {
			public void run() {
			}
		};

		aboutAction = new Action(resourceBundle
				.getString(LocaleResources.ACTION_ABOUT)) {
			public void run() {
				AboutDialog aboutDialog = new AboutDialog(getShell());
				aboutDialog.setBlockOnOpen(true);
				aboutDialog.open();
			}
		};

		preferencesAction = new Action(resourceBundle
				.getString(LocaleResources.ACTION_PREFERENCES)) {
			public void run() {
			}
		};

		connectFepAction = new Action(resourceBundle.getString(LocaleResources.VAR_CONNECT)) {
			public void run() {
				commander.connect();
			}
		};

		disconnectfepAction = new Action(resourceBundle.getString(LocaleResources.VAR_DISCONNECT)) {
			public void run() {
				commander.close();
			}
		};

		getFepConnNumAction = new Action(resourceBundle.getString(LocaleResources.VAR_FEP_CONN_COUNT)) {
			public void run() {
			}
		};

		reloadnavitreeAction = new Action("refreshNaviTree") {
			public void run() {
				refreshNaviTree();
			}
		};

		refreshtermtableAction = new Action("refreshTermTable") {
			public void run() {
				refreshTermTable();
			}
		};

		refreshtasktableAction = new Action("refreshTaskTable") {
			public void run() {
				refreshTaskTable();
			}
		};

		refreshallframesAction = new Action("refreshAllFrames") {
			public void run() {
				List<FramePo> list = dataAccessor.queryAllFrames();
				refreshFrameTable(list);
			}
		};

		deleteconAction = new Action("deleteCon") {
//			public void run() {
//				IStructuredSelection selection = (IStructuredSelection) naviTreeViewer
//						.getSelection();
//				if (!selection.isEmpty()) {
//					Iterator iter = selection.iterator();
//					while (iter.hasNext()) {
//						taskVo = (TaskVo) iter.next();
//						if (dataAccessor.deleteTaskById(taskVo.getModel()
//								.getId()) == 0) {
//							taskList.remove(taskVo);
//							taskTableViewer.remove(taskVo);
//						}
//					}
//				}
//			}
		};
	}

	@Override
	protected MenuManager createMenuManager() {
		MenuManager menuManager = new MenuManager();

		final MenuManager fileMenuManager = new MenuManager(resourceBundle
				.getString(LocaleResources.MENU_FILE));
		menuManager.add(fileMenuManager);
		fileMenuManager.add(exitAction);

		final MenuManager actionMenuManager = new MenuManager(resourceBundle
				.getString(LocaleResources.MENU_ACTION));
		menuManager.add(actionMenuManager);

		actionMenuManager.add(minimizeAction);

		actionMenuManager.add(maximizeAction);

		actionMenuManager.add(new Separator());

		actionMenuManager.add(reloadnavitreeAction);

		actionMenuManager.add(refreshtermtableAction);

		actionMenuManager.add(refreshtasktableAction);

		actionMenuManager.add(refreshallframesAction);

		final MenuManager toolMenuManager = new MenuManager(resourceBundle
				.getString(LocaleResources.MENU_TOOL));
		menuManager.add(toolMenuManager);

		toolMenuManager.add(preferencesAction);

		final MenuManager fepManager = new MenuManager(resourceBundle.getString(LocaleResources.MENU_FEP));
		menuManager.add(fepManager);

		fepManager.add(connectFepAction);

		fepManager.add(disconnectfepAction);

		fepManager.add(new Separator());

		fepManager.add(getFepConnNumAction);

		final MenuManager helpMenuManager = new MenuManager(resourceBundle
				.getString(LocaleResources.MENU_HELP));
		menuManager.add(helpMenuManager);

		helpMenuManager.add(welcomeAction);

		helpMenuManager.add(aboutAction);

		return menuManager;
	}

	@Override
	protected ToolBarManager createToolBarManager(int style) {
		ToolBarManager toolBarManager = new ToolBarManager(style);
		toolBarManager.add(exitAction);

		return toolBarManager;
	}

	@Override
	protected StatusLineManager createStatusLineManager() {
		StatusLineManager statusLineManager = new StatusLineManager();
		statusLineManager.setMessage(null, "");
		return statusLineManager;
	}

	public static final void show() {
		PropertyConfigurator.configure("log4j.properties");
		final ApplicationContext context = SpringUtil.getApplicationContext();
		Realm.runWithDefault(SWTObservables.getRealm(Display.getDefault()),
				new Runnable() {
					public void run() {
						try {
							final ToolkitWindow window = (ToolkitWindow) context
									.getBean("toolkitWindow");
							window.setBlockOnOpen(true);
							window.open();
							// Display.getCurrent().dispose();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
	}

	public static void main(String args[])  {
 		Display display = Display.getDefault();
 		Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
 			public void run() {
 				show();
 			}
 		});
 	}


	@Override
	protected void configureShell(Shell shell) {
		super.configureShell(shell);
		SWTUtil.setCenter(shell);
		shell.setText(resourceBundle.getString(LocaleResources.PROGRAM_TOOLKIT_TITLE));
		shell.setImage(imageRegistry.get(ImageRegistryFactory.IMAGE_KAIFA_LOGO));
	}


	public void setImageRegistry(ImageRegistry imageRegistry) {
		this.imageRegistry = imageRegistry;
	}
	

	public void setTreeFactory(TreeFactory treeFactory) {
		this.treeFactory = treeFactory;
	}

	public void setTermListFactory(TermListFactory termListFactory) {
		this.termListFactory = termListFactory;
	}

	public void setTaskListFactory(TaskListFactory taskListFactory) {
		this.taskListFactory = taskListFactory;
	}
	public void setDataAccessor(DataAccessor dataAccessor) {
		this.dataAccessor = dataAccessor;
	}

	protected DataBindingContext initDataBindings() {
		// JFace data binding
		BeansListObservableFactory treeViewerListFactory = new BeansListObservableFactory(ObservableTreeNode.class, "children");
		TreeBeanAdvisor treeViewerAdvisor = new TreeBeanAdvisor(ObservableTreeNode.class, null, "children", null);
		ObservableListTreeContentProvider treeViewerListContentProvider = new ObservableListTreeContentProvider(treeViewerListFactory, treeViewerAdvisor);
		naviTreeViewer.setContentProvider(treeViewerListContentProvider);
		//
		naviTreeViewer.setLabelProvider(new TreeObservableLabelProvider(treeViewerListContentProvider.getKnownElements(), ObservableTreeNode.class, "label", null));
		//
		refreshNaviTree();
		//
		ObservableListContentProvider termTableViewerContentProviderList = new ObservableListContentProvider();
		termTableViewer.setContentProvider(termTableViewerContentProviderList);
		//
		IObservableMap[] termTableViewerLabelProviderMaps = BeansObservables.observeMaps(termTableViewerContentProviderList.getKnownElements(), TermVo.class, TermVo.fields());
		termTableViewer.setLabelProvider(new ObservableMapLabelProvider(termTableViewerLabelProviderMaps));
		//
		refreshTermTable();
		//
		ObservableListContentProvider taskTableViewerContentProviderList = new ObservableListContentProvider();
		taskTableViewer.setContentProvider(taskTableViewerContentProviderList);
		//
		IObservableMap[] taskTableViewerLabelProviderMaps = BeansObservables.observeMaps(taskTableViewerContentProviderList.getKnownElements(), TaskVo.class, new String[]{"taskType", "runDate"});
		taskTableViewer.setLabelProvider(new ObservableMapLabelProvider(taskTableViewerLabelProviderMaps));
		//
		refreshTaskTable();
		// SWT data binding
		DataBindingContext bindingContext = new DataBindingContext();
		//
		IObservableValue hostTextTextObserveWidget = SWTObservables.observeText(hostText, SWT.Modify);
		IObservableValue commanderHostObserveValue = BeansObservables.observeValue(commander, "host");
		IObservableValue portTextTextObserveWidget = SWTObservables.observeText(portText, SWT.Modify);
		IObservableValue commanderPortObserveValue = BeansObservables.observeValue(commander, "port");
		IObservableValue hostTextEditableObserveWidget = SWTObservables.observeEditable(hostText);
		IObservableValue portTextEditableObserveWidget = SWTObservables.observeEditable(portText);
		IObservableValue connectButtonEnabledObserveWidget = SWTObservables.observeEnabled(connectButton);
		IObservableValue closeButtonEnabledObserveWidget = SWTObservables.observeEnabled(closeButton);
		IObservableValue funcGroupEnableObservWidget = SWTObservables.observeEnabled(funcGroup);
		IObservableValue commanderConnectedObserveValue = BeansObservables.observeValue(commander, "connected");
		
		bindingContext.bindValue(hostTextTextObserveWidget, commanderHostObserveValue, null, null);
		
		UpdateValueStrategy textToPortStrategy = new UpdateValueStrategy();
		textToPortStrategy.setConverter(StringToNumberConverter.toInteger(true));
		UpdateValueStrategy portToTextStrategy = new UpdateValueStrategy();
		portToTextStrategy.setConverter(NumberToStringConverter.fromInteger(true));
		bindingContext.bindValue(portTextTextObserveWidget, commanderPortObserveValue, textToPortStrategy, portToTextStrategy);
		
		UpdateValueStrategy booleanStrategy = new UpdateValueStrategy();
		booleanStrategy.setConverter(new BooleanConverter());

		bindingContext.bindValue(hostTextEditableObserveWidget, commanderConnectedObserveValue, null, booleanStrategy);
		bindingContext.bindValue(portTextEditableObserveWidget, commanderConnectedObserveValue, null, booleanStrategy);
		bindingContext.bindValue(connectButtonEnabledObserveWidget, commanderConnectedObserveValue, null, booleanStrategy);
		bindingContext.bindValue(closeButtonEnabledObserveWidget, commanderConnectedObserveValue, null, null);
		bindingContext.bindValue(funcGroupEnableObservWidget, commanderConnectedObserveValue, null, null);
		//
		return bindingContext;
	}
	
	private void refreshNaviTree() {
		treeData = treeFactory.create();
		WritableList listWritableList = new WritableList(treeData, ObservableTreeNode.class);
		naviTreeViewer.setInput(listWritableList);
	}
	
	private void refreshTermTable() {
		termList = termListFactory.create();
		WritableList termsWritableList = new WritableList(termList, TermVo.class);
		termTableViewer.setInput(termsWritableList);
	}
	
	private void refreshTaskTable() {
		taskList = taskListFactory.create();
		WritableList tasksWritableList = new WritableList(taskList, TaskVo.class);
		taskTableViewer.setInput(tasksWritableList);
	}
	
	public void refreshFrameTable(List list) {
		WritableList tasksWritableList = new WritableList(list, FrameVo.class);
		frameTableViewer.setInput(tasksWritableList);
	}
}
